package com.zhr.httpd;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

import com.zhr.server.WeixinRequest;
import com.zhr.server.WeixinResponse;
import com.zhr.server.WeixinServer;
import com.zhr.util.Encrypter;

public class WeixinHTTPD extends NanoHTTPD {

	private final String TOKEN = "zhrweixintest";

	private WeixinServer weixinServer;
	
	public WeixinHTTPD(int port,WeixinServer weixinServer) throws IOException {
		super(port, null);
		this.weixinServer = weixinServer;
	}

	@Override
	public Response serve(String uri, String method, Properties header,
			Properties parms, Properties files) {
		System.out.println(method + " '" + uri + "' ");

		Enumeration e = header.propertyNames();
		while (e.hasMoreElements()) {
			String value = (String) e.nextElement();
			System.out.println("  HDR: '" + value + "' = '"
					+ header.getProperty(value) + "'");
		}
		e = parms.propertyNames();
		while (e.hasMoreElements()) {
			String value = (String) e.nextElement();
			System.out.println("  PRM: '" + value + "' = '"
					+ parms.getProperty(value) + "'");
		}
		e = files.propertyNames();
		while (e.hasMoreElements()) {
			String value = (String) e.nextElement();
			System.out.println("  UPLOADED: '" + value + "' = '"
					+ files.getProperty(value) + "'");
		}
		String response = "";
		String contentType = MIME_HTML;
		String timestamp = String.valueOf(parms.get("timestamp"));
		String nonce = String.valueOf(parms.get("nonce"));
		String signature = String.valueOf(parms.get("signature"));
		String echostr = String.valueOf(parms.get("echostr"));
		String xml = String.valueOf(parms.get("xml"));
		if (null != parms.get("echostr")) {
			contentType = MIME_HTML;
			Encrypter encrypter = new Encrypter(TOKEN, timestamp, nonce,
					signature, echostr);
			if (encrypter.validate()) {
				response = encrypter.getEchostr();
			}
		}else if(null != xml && !"".equals(xml)){
			contentType = MIME_XML;
			WeixinResponse weixinResponse= weixinServer.execute(new WeixinRequest(xml));
			response = weixinResponse.toString();
		}
		System.out.println("response:");
		System.out.println(response);
		return new NanoHTTPD.Response(HTTP_OK, contentType, response);
	}
}
